package com.yonyou.ucf.mdf.app.isvdxq.secondpart.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.gson.Gson;
import com.yonyou.ucf.mdf.app.isvdxq.ReturnResult.DataResult;
import com.yonyou.ucf.mdf.app.isvdxq.common.DxqConfig;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.RFIDCodeDetail.entity.ReRFIDCode;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.RFIDCodeDetail.entity.RfidCodebind;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.RFIDCodeDetail.model.ShangjiaList;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.RFIDCodeDetail.service.RfidCodeDetailService;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.guize.service.GuiZeService;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.entity.OrderNoticeEntity;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.service.OrderNoticeService;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.stock.service.StockService;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.BaseService;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.entity.EpcEntity;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.entity.StorerecordEntity;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.entity.TaglistEntity;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.model.*;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.service.EpclistService;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.service.StorerecordService;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.service.TaglistService;
import com.yonyou.ucf.mdf.app.isvdxq.utils.MyTool;
import com.yonyou.ucf.mdf.app.isvdxq.utils.RequestTool;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 容器信息
 */
@RestController
@RequestMapping(value = {DxqConfig.pre_apiUrl+"/taglist",DxqConfig.pre_pcUrl+"/taglist"})
public class TaglistController {
    private static final Logger logger = LoggerFactory.getLogger(TaglistController.class);
    @Autowired
    BaseService baseService;
    @Autowired
    TaglistService taglistService;
    @Autowired
    EpclistService epclistService;
    @Autowired
    GuiZeService guiZeService;

    @RequestMapping("/ViewPage")
    public DataResult ViewPage(HttpServletRequest request) {
        DataResult result = new DataResult(0, "操作失败");
        //接收参数
        String tenantId = baseService.getTenantId(request);
        String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
        try {
            Map params = RequestTool.getParamsPage(request, result);
            int pagenum = result.getPageNum();
            int pagesize = result.getPageSize();
            int m = result.initStartNumber();
            List<TaglistEntity> dataList = taglistService.SelectPage(tenantId, m, pagesize);
            result = new DataResult(1, "操作成功");
            result.setDataList(dataList);
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }

    /**
     * 所有数据列表
     *
     * @param request
     * @return
     */
    @RequestMapping("/ViewList")
    public DataResult ViewList(HttpServletRequest request) {
        DataResult result = new DataResult(0, "操作失败");
        //接收参数
        String tenantId = baseService.getTenantId(request);
        String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
        List<TaglistEntity> dataList = taglistService.SelectAll(tenantId);
        result = new DataResult(1, "操作成功");
        result.setDataList(dataList);

        return result;
    }

    /**
     * 拆托 [epc,...]
     *
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/DelEpclist")
    public DataResult DelEpclist(@RequestBody List<String> strList, HttpServletRequest request) throws IOException {
        DataResult dataResult = new DataResult();
        //接收参数
        String tenantId = baseService.getTenantId(request);
        String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);

        Map<String, Object> reqParams = RequestTool.getParams(request);
        String tag = (String) reqParams.get("tag");
        String dataStr = (String) reqParams.get("data");
        List<Long> ids = new ArrayList<>();
        if (!StringUtils.isEmpty(dataStr)) {
            ids = RequestTool.getBean(dataStr, new TypeReference<List<Long>>() {
            });
        }
        if (strList.size() == 0) return dataResult;
        //删除合法范围内的数据
        final List<String> epclist_del = strList;
        List<TaglistEntity> dataList = taglistService.SelectByTag(tag, tenantId);
        ids = dataList.stream().filter(it -> epclist_del.contains(it.getCoderfid()))
                .map(e -> e.getId()).collect(Collectors.toList());
//        List<EpcEntity> tempEpcList = taglistService.SelectEpcEntityByEpcs(strList,tenantId);
//        List<String> temp_ids = tempEpcList.stream().map(it->it.getId()).distinct().collect(Collectors.toList());
        //tag ids
        int rInt = taglistService.DeleteByIds(ids, tenantId);
        if (rInt <= 0) return dataResult;

        dataResult.setStatus(1);
        dataResult.setMessage("操作成功");

        return dataResult;
    }

    /**
     * 移托 [epc,...]
     * 如果新托盘有货位信息，更新物料库存信息；
     * tag 托盘信息，可为： 1在库托盘；2新托盘
     *
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/RemoveEpclist")
    public DataResult RemoveEpclist(@RequestBody List<String> strList, HttpServletRequest request) throws Exception {
        DataResult dataResult = new DataResult(0, "操作失败");
        try {
            //接收参数
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            Map<String, Object> reqParams = RequestTool.getParams(request);
            String tag = (String) reqParams.get("tag");//新托盘
            String modifier = (String) reqParams.get("modifier");
            if (StringUtils.isEmpty(userId)) userId = modifier;
            if (strList.size() == 0) {
                dataResult.setMessage("操作数据异常");
                return dataResult;
            }
            //修改托盘tag信息 货品信息
            List<EpcEntity> epcEntities = epclistService.SelectByEpcs(strList, tenantId);
            List<Integer> statusList = epcEntities.stream().map(it -> it.getRfid_status()).distinct().collect(Collectors.toList());
            if (statusList.size() > 1) {
                dataResult.setMessage("操作数据不合法");
                return dataResult;
            }
            int rInt = taglistService.RomoveByIds(strList, tenantId, userId, tag);

            dataResult.setStatus(1);
            dataResult.setMessage("操作成功");
        } catch (Exception ex) {
            dataResult.setMessage(ex.getMessage());
        }

        return dataResult;
    }

    @Autowired
    private RfidCodeDetailService rfidCodeDetailService;

    /**
     * 托盘收货绑签
     * 到货签收 产生批次号 批次号推送用友验证唯一
     * 返回接收批次号
     *
     * @param tag
     * @param CodeBindList
     * @return
     */
    @PostMapping("/SubmitBindReRFIDCodeByTag")
    public DataResult SubmitBindReRFIDCodeByTag(String tag, @RequestBody List<RfidCodebind> CodeBindList, HttpServletRequest request) {
        DataResult dataResult = new DataResult(0, "操作异常");
        try {
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            RfidCodebind tempEntity = CodeBindList.get(0);
            String operuserId = tempEntity.getModifier();
            if (StringUtils.isEmpty(userId)) userId = operuserId;
            String opername = tempEntity.getModifier();
            String orgId = tempEntity.getOrgId();

            List<String> strList =
                    CodeBindList.stream().map(it -> it.getRfid_code()).distinct().collect(Collectors.toList());
            List<TaglistEntity> dataList = new ArrayList<>();
            //数据组装
            List<TaglistEntity> tempList = taglistService.SelectByEpcs(strList, tenantId);
            dataList = TaglistService.CreateEntityByEpc(strList, tempList, tenantId, userId, opername, tag, orgId);

            int rInt = taglistService.InsertBatch(dataList);
            if (rInt <= 0) return dataResult;

            dataResult.setStatus(1);
            dataResult.setMessage("操作成功");

            String ordertype = CodeBindList.get(0).getOrdertype();
            String orderid = CodeBindList.get(0).getOrderid();
            if (StringUtils.isEmpty(orderid) || StringUtils.isEmpty(ordertype)) {
                dataResult.setMessage("数据异常，必须有单号和单据类型");
                return dataResult;
            }
            List<StorerecordEntity> daohuoList = storerecordService.getDaohuoList(orderid, tenantId, userId);
            String pickbatchno = "";//私有接受批次
            if (daohuoList == null || daohuoList.size() == 0) pickbatchno = MyTool.GenerateBatchnoDXQ(ordertype);
            else pickbatchno = daohuoList.get(0).getBatchno_dxq();

            String batchNum = MyTool.GenerateBatchnoDXQ(ordertype);//私有发签批次
            //入库发签作业
            dataResult = rfidCodeDetailService.BindRfidCode(CodeBindList, batchNum, pickbatchno);
            dataResult.setData(pickbatchno);
            if (dataResult.getStatus() != 1) {
                List<String> epcs = dataList.stream().map(it -> it.getCoderfid()).collect(Collectors.toList());
                taglistService.DeleteByEpcs(epcs, tenantId);
            }
        } catch (Exception ex) {
            dataResult.setMessage(ex.getMessage());
        }
        return dataResult;
    }

    /**
     * 合托 [epc,...]
     *
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/AddEpclist")
    public DataResult AddEpclist(@RequestBody List<String> strList, HttpServletRequest request) throws IOException {
        DataResult dataResult = new DataResult();
        //接收参数
        String tenantId = baseService.getTenantId(request);
        String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);

        Map<String, Object> reqParams = RequestTool.getParams(request);
        String tag = (String) reqParams.get("tag");
        String modifier = (String) reqParams.get("modifier");
        String orgId = (String) reqParams.get("orgId");
        String operuserId = modifier;//yhtuserid
        String opername = (String) reqParams.get("modifierName");
        String dataStr = (String) reqParams.get("data");//[id,...]
        List<String> ids = new ArrayList<>();
        if (!StringUtils.isEmpty(dataStr)) {
            ids = RequestTool.getBean(dataStr, new TypeReference<List<String>>() {
            });
        }
        if (strList.size() == 0) return dataResult;
        List<TaglistEntity> dataList = new ArrayList<>();
        //数据组装
        List<TaglistEntity> tempList = taglistService.SelectByEpcs(strList, tenantId);
        dataList = TaglistService.CreateEntityByEpc(strList, tempList, tenantId, operuserId, opername, tag, orgId);

        int rInt = taglistService.AddEpcToTag(dataList, tag, tenantId, modifier);
//        if (rInt <= 0) return dataResult;

        dataResult.setStatus(1);
        dataResult.setMessage("操作成功");

        return dataResult;
    }

    /**
     * 查询托盘物料标签 tag
     *
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/GetEpclist")
    public DataResult GetEpclist(HttpServletRequest request) {
        DataResult dataResult = new DataResult(0, "操作失败");
        try {
            //接收参数
            String tenantId = baseService.getTenantId(request);

            Map<String, Object> reqParams = RequestTool.getParams(request);
            String tag = (String) reqParams.get("tag");
            //Tag查询EPC列表
            List<EpcEntityBean> myList = new ArrayList<>();
            List<TaglistEntity> dataList = taglistService.SelectByTag(tag, tenantId);
            dataResult.setStatus(1);
            dataResult.setMessage("操作成功");
            if (dataList != null && dataList.size() > 0) {
                List<String> strList = dataList.stream().map(it -> it.getCoderfid()).distinct().collect(Collectors.toList());
                List<EpcEntityBean> tempList = taglistService.SelectInfoByEpcs(strList, tenantId);
                myList = tempList.stream().filter(it -> strList.contains(it.getRfid_code()))
                        .collect(Collectors.toList());
            }
            dataResult.setDataList(myList);
        } catch (Exception ex) {
            dataResult.setMessage(ex.getMessage());
        }
        return dataResult;
    }

    /**
     * 物料下架
     *
     * @return
     */
    @RequestMapping("/CleanBindReRFIDCode")
    public DataResult CleanBindReRFIDCode(EpcInParamBean paramBean, HttpServletRequest request) throws IOException {
        DataResult dataResult = new DataResult();
        //接收参数
        String tenantId = baseService.getTenantId(request);
        String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);

        Map<String, Object> reqParams = RequestTool.getParams(request);
        String modifier = (String) reqParams.get("modifier");
        String ids = (String) reqParams.get("ids");
        List<String> strList = new ArrayList<>(Arrays.asList(ids.split(",")));
        int rInt = taglistService.CleanEpclist(strList, modifier, tenantId);
        if (rInt <= 0) return dataResult;

        dataResult.setStatus(1);
        dataResult.setMessage("操作成功");
        return dataResult;
    }

    /**
     * 批量修改EPC
     * 暂未使用
     * @return
     */
    @RequestMapping("/EditEpclistBatch")
    public DataResult EditEpclistBatch(EpcInParamBean paramBean, HttpServletRequest request) throws IOException {
        DataResult dataResult = new DataResult();
        //接收参数
        String tenantId = baseService.getTenantId(request);
        String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);

        Map<String, Object> reqParams = RequestTool.getParams(request);
        String modifier = (String) reqParams.get("modifier");
        int rInt = taglistService.EditEpclistBatch(paramBean, modifier, tenantId);
        if (rInt <= 0) return dataResult;

        dataResult.setStatus(1);
        dataResult.setMessage("操作成功");
        return dataResult;
    }

    /**
     * 同批同品同货位
     *
     * @param paramBean
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/EditEpclist")
    public DataResult EditEpclist(EpcInParamBean paramBean, HttpServletRequest request) throws IOException {
        DataResult dataResult = new DataResult();
        //接收参数
        String tenantId = baseService.getTenantId(request);
        String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);

        Map<String, Object> reqParams = RequestTool.getParams(request);
        String modifier = (String) reqParams.get("modifier");
        String ids = (String) reqParams.get("ids");
        List<String> strList = new ArrayList<>(Arrays.asList(ids.split(",")));
        int rInt = taglistService.EditEpclist(paramBean, strList, modifier, tenantId);
        if (rInt <= 0) return dataResult;

        dataResult.setStatus(1);
        dataResult.setMessage("操作成功");
        return dataResult;
    }

    /**
     * 批量解绑EPC接口
     * ordertype=4 盘点补录物资解绑
     *
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/JieBindReRFIDCode")
    public DataResult JieBindReRFIDCode(HttpServletRequest request) throws Exception {
        DataResult dataResult = new DataResult();
        //接收参数
        String tenantId = baseService.getTenantId(request);
        String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);

        Map<String, Object> reqParams = RequestTool.getParams(request);
        String modifier = (String) reqParams.get("modifier");
        if (StringUtils.isEmpty(userId)) userId = modifier;
        String ids = (String) reqParams.get("ids"); //EPC ids
        String ordertype = (String) reqParams.get("ordertype");
        if (StringUtils.isEmpty(ordertype)) ordertype = "3";
        ids = URLDecoder.decode(ids, "utf-8");
        List<String> ids_epc = new ArrayList<>(Arrays.asList(ids.split(",")));
        //验证标签是否可以执行销毁操作
        boolean flag = taglistService.CheckEpcDestory(ids_epc, ordertype, tenantId);
        if (!flag) {
            dataResult = new DataResult(0, "要删除的物料标签已到货提交,不允许删除！");
            return dataResult;
        }
        //执行销毁作业
        int rInt = taglistService.EditEpclistDestory(ids_epc, ordertype, userId, tenantId);

        dataResult.setStatus(1);
        dataResult.setMessage("操作成功");
        return dataResult;
    }

    /**
     * 获取Epc信息数据 用于复核
     *
     * @param orderid
     * @param ordertype
     * @param tag
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/GetEpcinfolist")
    public DataResult GetEpcinfolist(String orderid, String ordertype, String tag, HttpServletRequest request) throws Exception {
        DataResult dataResult = new DataResult<>();
        //接收参数
        String tenantId = baseService.getTenantId(request);
        //验证单据状态
        DataResult tempRes = guiZeService.SelectOrderAuditStatus(orderid, ordertype);
        JSONObject res = JSONObject.parseObject(new Gson().toJson(tempRes));
        //获取数据
        List<EpcBean> dataList = taglistService.GetEpcinfolist(orderid, ordertype, tag, tenantId, null);

        dataResult.setStatus(1);
        dataResult.setMessage("操作成功");
        dataResult.setDataList(dataList);
        dataResult.setOrderAuditType(tempRes.getOrderAuditType());//单据审核状态 0 未审核 1已审核 2已弃审，用于判断单据是否弃审
        return dataResult;
    }

    /**
     * 拣货货位提示接口
     * GetEpcTip
     *
     * @return
     */
    @RequestMapping("/GetEpcinfoByPoint")
    public DataResult<EpcBean> GetEpcinfoByPoint(String tag, HttpServletRequest request) throws Exception {
        DataResult<EpcBean> dataResult = new DataResult<>();
        //接收参数
        String tenantId = baseService.getTenantId(request);

        Map<String, Object> reqParams = RequestTool.getParams(request);
        String locationId = (String) reqParams.get("locationId");
        String batchno = (String) reqParams.get("batchno");
        List<String> localtionIds = new ArrayList<>();
        if (!StringUtils.isEmpty(locationId)) localtionIds = taglistService.GetLocationListByPath(locationId, tenantId);
        List<String> proids = new ArrayList<>();
        List<Object> prolist = (List<Object>) reqParams.get("prolist"); //product_id,product_sku_id,batchno
        List<EpcBean> tempList = JSONArray.parseArray(JSONObject.toJSONString(prolist), EpcBean.class);
        for (EpcBean entity : tempList) {
            proids.add(entity.getProduct_id() + "|" + entity.getProduct_sku_id());
        }
        List<EpcBean> dataList = taglistService.GetEpctiplist(proids, localtionIds, batchno, tenantId);
        // 提示规则：到期先出


        dataResult.setStatus(1);
        dataResult.setMessage("操作成功");
        dataResult.setDataList(dataList);
        return dataResult;
    }

    /**
     * [EPC 上架] 入库物资上架，修改货位和物资库存状态
     * @param epcList
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/ShangjiadReRFIDCode")
    public DataResult ShangjiadReRFIDCode(@RequestBody List<EpcParamOnBean> epcList, HttpServletRequest request) throws Exception {
        DataResult dataResult = new DataResult<>();
        dataResult.setStatus(0);
        dataResult.setMessage("操作失败");
        //接收参数
        String tenantId = baseService.getTenantId(request);
        // 获取无托盘数据 epcIds
        List<String> ids = epcList.stream().map(it -> it.getId()).distinct().collect(Collectors.toList());

        EpcParamOnBean tempEpc = epcList.get(0);
        ShangjiaList obj = new ShangjiaList();
        obj.setId(String.join(",", ids));
        obj.setLocationId(tempEpc.getLocationId());
        obj.setModifier(tempEpc.getModifier());

        String ordertype = "3";
        dataResult = rfidCodeDetailService.EditEpcForShangjia(obj.getId(), obj.getLocationId(), ordertype, obj.getModifier(), tenantId);
        return dataResult;
    }

    @Autowired
    StockService stockService;

    /**
     * 托盘查询单据物料信息
     * @param tag
     * @param orderId
     * @param ordertype
     * @param warehouseIds
     * @param request
     * @return
     */
    @RequestMapping("/GetGoodsByLabelCode")
    public DataResult GetEpclistByTag(String tag, String orderId, String ordertype, String warehouseIds, HttpServletRequest request) {
        DataResult dataResult = new DataResult(0, "操作失败");
        try {
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            List<String> warehouseIds1 = baseService.getWarehouseIds(userId, tenantId);
            List<String> warehouseIdsArray = warehouseIds1;
            if (!StringUtils.isEmpty(warehouseIds)){
                warehouseIdsArray = Arrays.asList(warehouseIds.split(","));
            }
            Map<String, String> reqParams = RequestTool.getParams(request);
            List<String> strList = taglistService.SelectEpcByTag(tag, tenantId);
            dataResult = stockService.CheckGoodsByLabelCode(strList, orderId, ordertype, warehouseIdsArray, tenantId);
        } catch (Exception ex) {
            dataResult.setMessage(ex.getMessage());
        }
        return dataResult;
    }

    @Autowired
    private OrderNoticeService orderNoticeService;
    @Autowired
    private StorerecordService storerecordService;

    /**
     * 拣货完成 写入本地通知表 dxq_ordernotice 通知相关人员配货
     * 生成配货通知单：单发货单可以下推多个拣货出库单
     *
     * @param orderid
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/InsertAllotOrderNotice")
    public DataResult InsertAllotOrderNotice(String orderid, HttpServletRequest request) throws Exception {
        DataResult result = new DataResult(0, "参数异常");
        try {
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            String modifier = (String) request.getParameter("modifier");
            if (StringUtils.isEmpty(userId)) userId = modifier;
            // 拣货记录信息更新拣货完成时间、拣货完成批次号
            OrderNoticeEntity entity = new OrderNoticeEntity();
            entity.setTenant_id(tenantId);
            entity.setType(DxqConfig.AllotOk);
            entity.setDr(0);
            entity.setAuditstatus(0);
            entity.setRepickstatus(1);
            entity.setModifier(userId);
            entity.setStatus(0);
            // 获取当前拣货EPC信息
            List<StorerecordEntity> datalist = new ArrayList<>();
            List<StorerecordEntity> tempdatalist = storerecordService.SelectByOrderid(orderid, tenantId, DxqConfig.PickOk);
            if (tempdatalist.size() == 0) {
                result.setMessage("没有待处理数据");
                return result;
            }
            StorerecordEntity modelEntity = tempdatalist.get(0);
            // 生成配货批次号
            String ordertype = modelEntity.getOrdertype();
            String picicode = MyTool.GenerateBatchnoDXQ(ordertype);
            entity.setPickbatchno(picicode); // 不对应 storerecord表 pickbatchno 字段
            for (StorerecordEntity item : tempdatalist) {
                StorerecordEntity data = MyTool.convertBean2Bean(item, StorerecordEntity.class);
                data.setModifier(modifier);
                data.setPickstatus(1); // 拣货完成
                if (StringUtils.isEmpty(data.getStockId())) {
                    data.setStockId(item.getWarehouse_id());
                }
                datalist.add(data);
            }
            entity.setOrderid(modelEntity.getOrderid());
            entity.setOrdercode(modelEntity.getOrdercode());
            entity.setOrderdetailids(modelEntity.getOrderdetailid());
            entity.setTranstype(modelEntity.getTranstype());
            String keysEpcId = datalist.stream().map(it -> it.getRfidcodeId()).collect(Collectors.joining(","));
            String keysEpcs = datalist.stream().map(it -> it.getRfidcode()).collect(Collectors.joining(","));
            entity.setActioncode("allot"); //自定义通知单据
            Map<String, Object> remarkDxq = new HashMap<>();
            remarkDxq.put("warehouseId", modelEntity.getStockId());
            remarkDxq.put("epcIds", keysEpcId);
            remarkDxq.put("epcs", keysEpcs);
            entity.setRemarkdxq(JSONObject.toJSONString(remarkDxq));
            entity.setFirstsourceid(modelEntity.getFirstsourceid());
            entity.setSourceid(modelEntity.getSourceid());
            // 写入配货通知
            int rInt = orderNoticeService.insertSelective(entity, datalist, tenantId);
            result = new DataResult(1, "操作成功");
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }

    /**
     * 获取待配货单据列表，一个单据可以多次配货发车
     * status=0 未完成出库单据
     *
     * @param request
     * @return
     */
    @RequestMapping("/GetAllotOrderList")
    public DataResult GetAllotOrderList(HttpServletRequest request) {
        String tenantId = baseService.getTenantId(request);
        DataResult result = new DataResult(0, "参数异常");
        List<OrdernoticeBean> myList = new ArrayList<>();
        try {
            List<OrderNoticeEntity> dataList = orderNoticeService.SelectByOrderType(DxqConfig.AllotOk, tenantId);
            for (OrderNoticeEntity item : dataList) {
                if (item.getRepickstatus() == 1) {
                    OrdernoticeBean entity = new OrdernoticeBean();
                    entity.setAuditstatus(item.getAuditstatus());
                    entity.setId(item.getId());
                    entity.setOrdercode(item.getOrdercode());
                    entity.setOrderid(item.getOrderid());
                    entity.setPickbatchno(item.getPickbatchno());
                    entity.setTranstype(item.getTranstype());
                    entity.setType(item.getType());
                    entity.setWarehouseId(item.getActioncode());
                    if (!StringUtils.isEmpty(item.getRemarkdxq())) {
                        JSONObject jsonObject = JSONObject.parseObject(item.getRemarkdxq());
                        entity.setEpcids(jsonObject.getString("epcIds"));
                    }
                    entity.setTenantId(item.getTenant_id());
                    myList.add(entity);
                }
            }
            result = new DataResult(1, "操作成功");
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        result.setDataList(myList);

        return result;
    }

    /**
     * 复核 拣货托盘配货提交 多次提交
     * 一托盘一配货、EPCs配货
     * 多拣货批次同时配货验证
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/AllotEpcByTag")
    public DataResult AllotEpcByTag(HttpServletRequest request) throws Exception {
        DataResult dataResult = new DataResult<>(0, "操作失败");
        //提交数据需保证数据一致性tag归属订单
        try {
            //接收参数
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            Map<String, Object> reqParams = RequestTool.getParams(request);
            String orderid = (String) reqParams.get("orderid");
            String allotId = (String) reqParams.get("allotid");
            String modifier = (String) reqParams.get("modifier");
            String pickbatchno = (String) reqParams.get("pickbatchno"); //配货批次
            if (StringUtils.isEmpty(userId)) userId = modifier;
            if (StringUtils.isEmpty(orderid)) {
                dataResult.setMessage("orderid参数异常");
                return dataResult;
            }
            // 配货单验证
            OrderNoticeEntity entity = null;
            if (!StringUtils.isEmpty(allotId))
                entity = orderNoticeService.selectById(Integer.parseInt(allotId));
            if (!StringUtils.isEmpty(orderid) && !StringUtils.isEmpty(pickbatchno)) {
                List<OrderNoticeEntity> orderNoticeEntities = orderNoticeService.SelectByBatchno(orderid, pickbatchno, DxqConfig.AllotOk, tenantId);
                if (orderNoticeEntities.size() != 1) {
                    return dataResult;
                }
                entity = orderNoticeEntities.get(0);
            }
            if (entity == null) {
                dataResult.setMessage("配货单不存在");
                return dataResult;
            }
            // epcList
            List<String> strList = new ArrayList<>();
            // Tag查询EPC列表
            String tag = (String) reqParams.get("tag");
            if (!StringUtils.isEmpty(tag)) {
                List<EpcEntity> epcEntitys = taglistService.SelectInfoByTag(tag, tenantId);
                strList = epcEntitys.stream().map(it -> it.getRfid_code())
                        .distinct().collect(Collectors.toList());
            }
            //兼容EPC
            String dataStr = (String) reqParams.get("data");//epc,...
            if (!StringUtils.isEmpty(dataStr)) {
                strList = Arrays.asList(dataStr.split(","));
            }
            if (strList.size() == 0) {
                dataResult.setMessage("数据异常");
                return dataResult;
            }
            // 操作记录验证 已拣货待配货数据查询
            List<StorerecordEntity> storerecordEntities = storerecordService.selectStorerecordByEpcs(strList, 2, DxqConfig.PickOk, tenantId);
            if (storerecordEntities.size() == 0) {
                dataResult.setMessage("单据记录异常");
                return dataResult;
            }
            String finalOrderid = orderid;
            List<String> orderids = storerecordEntities.stream()
                    .filter(it -> !it.getOrderid().equals(finalOrderid))
                    .map(it -> it.getOrderid())
                    .distinct().collect(Collectors.toList());
            if (orderids.size() > 0) {
                dataResult.setMessage("不支持多单同时作业");
                return dataResult;
            }
            //配货完成即发货 拣货单审核 即配货完成 多次提交 status 4-5
            int checkNum = orderNoticeService.CheckAuditstatusByEntity(entity, storerecordEntities, tenantId, userId);
            // 检测更新配货单状态 支持多次配货
            List<StorerecordEntity> epcOther = storerecordService.selectStorerecordByEpcs(strList, 2, DxqConfig.PickOk, tenantId);
            if (epcOther.size() == 0) {
                entity.setAuditstatus(1);
                entity.setModifier(userId);
                orderNoticeService.updateByPrimaryKey(entity);
            }
            dataResult.setStatus(1);
            dataResult.setMessage("操作成功");
        } catch (Exception ex) {
            dataResult.setMessage(ex.getMessage());
        }
        return dataResult;
    }


    /**
     * 待发货详情
     *
     * @param request
     * @return
     */
    @RequestMapping("/GetAllotDetail")
    public DataResult GetAllotDetail(HttpServletRequest request) {
        DataResult result = new DataResult(0, "操作失败");
        try {
            //接收参数
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            Map<String, String> reqParams = RequestTool.getParams(request);
            String orderid = reqParams.get("orderid");
            String pickbatchno = reqParams.get("pickbatchno");
            if (StringUtils.isEmpty(orderid) || StringUtils.isEmpty(pickbatchno)) {
                result.setMessage("参数异常");
                return result;
            }
            List<ReRFIDCode> list = taglistService.GetAllotDetail(orderid, pickbatchno, tenantId);
            result = new DataResult(1, "操作成功");
            result.setDataList(list);
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }
}
